package com.zzyl.exception;

import cn.hutool.core.util.ObjectUtil;
import com.zzyl.base.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */
@Slf4j
@Component
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    
    /**
     * 处理业务异常
     * @param e 自定义异常
     * @return 响应数据，包含错误代码和错误消息
     */
    @ExceptionHandler(BaseException.class)
    public ResponseResult<Object> handleBusinessException(BaseException e) {
        e.printStackTrace();
        if (ObjectUtil.isNotEmpty(e.getBasicEnum())) {
            log.error("自定义异常处理:{}", e.getBasicEnum().getMsg());
        }
        return ResponseResult.error(e.getBasicEnum());
    }
    
    /**
     * 处理运行时异常
     * @param e 运行时异常
     * @return  响应数据，包含错误代码和错误消息
     */
    @ExceptionHandler(RuntimeException.class)
    public ResponseResult<Object> handleRuntimeException(RuntimeException e) {
        log.error("运行时异常:",e);
        return ResponseResult.error(e.getMessage());
    }


    /**
     * 处理未知异常
     */
    @ExceptionHandler(Exception.class)
    public ResponseResult<Object> handleUnknownException(Exception e) {
        log.error("未知异常", e);
        if (ObjectUtil.isNotEmpty(e.getCause())) {
            log.error("其他未知异常:{}", e.getMessage());
        }
        return ResponseResult.error(e.getMessage());
    
    }
}
